<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 用户管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-input v-model="query.userId" placeholder="用户ID" class="handle-input mr10" @keyup.enter.native="handleSearch"></el-input>
                <el-input v-model="query.userAcct" placeholder="账号" class="handle-input mr10" @keyup.enter.native="handleSearch"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="el-button" icon="el-icon-delete" @click="handleReset">重置</el-button>
                <div class="right-items" style="float: right;">
                    <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
                </div>
            </div>
            <el-table
                    :data="tableData"
                    border
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                    @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="userId" label="用户ID" width="200" align="center"></el-table-column>
                <el-table-column prop="userAcct" label="账号" align="center"></el-table-column>
                <el-table-column prop="userNm" label="姓名" align="center"></el-table-column>
                <el-table-column v-if="false" prop="roleIds" label="角色ID" align="center" :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop="roleNms" label="角色" align="center" :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop="organNames" label="医院" align="center" :show-overflow-tooltip="true"></el-table-column>
                <el-table-column label="头像(查看大图)" align="center">
                        <template slot-scope="scope">
                            <el-image v-if="scope.row.imgTp == undefined"
                                    class="table-td-thumb"
                                    :src="imgDefault"
                                    @click="onPreview(imgDefault)"
                            ></el-image>
                            <el-image v-else
                                      class="table-td-thumb"
                                      :src="'data:image/'+ scope.row.imgTp +';base64,' + scope.row.imgData"
                                      @click="onPreview('data:image/'+ scope.row.imgTp +';base64,' + scope.row.imgData)"
                            ></el-image>
                            <el-image-viewer
                                    v-if="showViewer"
                                    :on-close="closeViewer"
                                    :url-list="srcList"/>
                        </template>
                </el-table-column>
                <el-table-column prop="istTm" label="插入时间" align="center"></el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                                type="text"
                                icon="el-icon-delete"
                                class="red"
                                @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :current-page="query.pageIndex"
                        :page-size="query.pageSize"
                        :total="pageTotal"
                        @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 新增弹出框 -->
        <el-dialog title="新增" :visible.sync="addVisible" width="30%" :close-on-click-modal="false">
            <el-form ref="addForm" :rules="addFormRules" :model="addForm" label-width="90px">
                <el-form-item label="账号:" prop="userAcct">
                    <el-input v-model="addForm.userAcct"></el-input>
                </el-form-item>
                <el-form-item label="密码:" prop="userPwd">
                    <el-input type="password" v-model="addForm.userPwd"></el-input>
                </el-form-item>
                <el-form-item label="确认密码:" prop="userQPwd">
                    <el-input  type="password" v-model="addForm.userQPwd"></el-input>
                </el-form-item>
                <el-form-item label="姓名:" prop="userNm">
                    <el-input v-model="addForm.userNm"></el-input>
                </el-form-item>
                <el-form-item label="邮箱:" prop="userMail">
                    <el-input v-model="addForm.userMail"></el-input>
                </el-form-item>
                <el-form-item label="角色:" prop="roleIds">
                    <el-select v-model="addForm.roleIds" multiple collapse-tags placeholder="请选择角色">
                        <el-option v-for="role in roles" :label="role.roleNm" :key="role.roleId" :value="role.roleId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="医院:" prop="organIds">
                    <el-select v-model="addForm.organIds" multiple collapse-tags placeholder="请选择医院">
                        <el-option v-for="organ in organs" :label="organ.organNm" :key="organ.organId" :value="organ.organId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="头像:">
                    <div class="user-header">
                        <input type="file" name="image" accept="image/*" @change='onchangeImgFun'
                               class="header-upload-btn user-header-com">
                        <img  alt="" :src='imgStr' class="user-header-img user-header-com">
                    </div>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAdd">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="30%" :close-on-click-modal="false">
            <el-form ref="editForm" :rules="editFormRules" :model="editForm" label-width="120px">
                <el-form-item label="账号:" prop="userAcct">
                    <el-input readonly v-model="editForm.userAcct"></el-input>
                </el-form-item>
                <el-form-item label="姓名:" prop="userNm">
                    <el-input v-model="editForm.userNm"></el-input>
                </el-form-item>
                <el-form-item label="邮箱:" prop="userMail">
                    <el-input v-model="editForm.userMail"></el-input>
                </el-form-item>
                <el-form-item label="角色:" prop="roleIds">
                    <el-select v-model="editForm.roleIds" multiple collapse-tags placeholder="请选择角色">
                        <el-option v-for="role in roles" :label="role.roleNm" :key="role.roleId" :value="role.roleId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="医院:" prop="organIds">
                    <el-select v-model="editForm.organIds" multiple collapse-tags placeholder="请选择医院">
                        <el-option v-for="organ in organs" :label="organ.organNm" :key="organ.organId" :value="organ.organId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="头像:">
                    <div class="user-header">
                        <input type="file" name="image" accept="image/*" @change='onchangeImgFunEdit'
                               class="header-upload-btn user-header-com">
                        <img  alt=""  :src='imgStrEdit' class="user-header-img user-header-com">
                    </div>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeEdit">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import { userData,doAdd,isNotExists,doDelete,isPwdTrue,doUpdate} from '../../../../api/system/user/user';
    import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
    import { getRoles } from '../../../../api/system/role/role';
    import { getOrgans } from '../../../../api/system/organ/organ';
    export default {
        name: 'user',
        data() {
            return {
                query: {
                    userId: '',
                    userAcct: '',
                    organIds: localStorage.getItem("ms_organIds"),
                    pageIndex: 1,
                    pageSize: 10
                },
                tableData: [],
                multipleSelection: [],
                delList: [],
                editVisible: false,
                addVisible: false,
                isUpdateImg:false,
                pageTotal: 0,
                addForm:{},
                editForm: {},
                idx: -1,
                id: -1,
                imgDefault: require("../../../../assets/img/user_img.gif"),
                imgStr: require('../../../../assets/upload.png'),
                isExistQuery:{
                    userAcct:'',
                },
                imgLen:'',
                imgStrEdit:require('../../../../assets/upload.png'),
                imgLenEdit:'',
                addFormRules: {
                    userAcct: [
                        { required: true, message: '请输入用户账号', trigger: 'blur' },
                        { pattern: /^[^\u4e00-\u9fa5]+$/, message: '不允许输入中文',trigger: 'blur'},
                        { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号',trigger: 'blur'},
                        { pattern: /[0-9a-zA-Z]{1,6}/, message: '只可以输入数字和字母',trigger: 'blur'},
                        { min: 1, max: 6, message: '长度在 1 到 6 个字符', trigger: 'blur' }
                    ],
                    userPwd: [
                        { required: true, message: '请输入用户密码', trigger: 'blur' },
                        { pattern: /^[^\u4e00-\u9fa5]+$/, message: '不允许输入中文',trigger: 'blur'},
                        { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号',trigger: 'blur'},
                        { pattern: /[0-9a-zA-Z]{1,6}/, message: '只可以输入数字和字母',trigger: 'blur'},
                        { min: 6, max: 6, message: '长度为6 个字符', trigger: 'blur' }
                    ],
                    userQPwd: [
                        { required: true, message: '请输入确认密码', trigger: 'blur' },
                        { pattern: /^[^\u4e00-\u9fa5]+$/, message: '不允许输入中文',trigger: 'blur'},
                        { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号',trigger: 'blur'},
                        { pattern: /[0-9a-zA-Z]{1,6}/, message: '只可以输入数字和字母',trigger: 'blur'},
                        { min: 6, max: 6, message: '长度为6 个字符', trigger: 'blur' }
                    ],
                    userNm: [
                        { required: true, message: '请输入用户姓名', trigger: 'blur' }
                    ],
                    roleIds: [
                        { required: true, message: '请选择角色', trigger: 'change' }
                    ],
                    organIds: [
                        { required: true, message: '请选择医院', trigger: 'change' }
                    ],
                },
                editFormRules: {
                    userAcct: [
                        { required: true, message: '请输入用户账号', trigger: 'blur' },
                        { pattern: /^[^\u4e00-\u9fa5]+$/, message: '不允许输入中文',trigger: 'blur'},
                        { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号',trigger: 'blur'},
                        { pattern: /[0-9a-zA-Z]{1,6}/, message: '只可以输入数字和字母',trigger: 'blur'},
                        { min: 1, max: 6, message: '长度在 1 到 6 个字符', trigger: 'blur' }
                    ],
                    userPwd: [
                        { required: true, message: '请输入用户密码', trigger: 'blur' },
                        { required: true, message: '请输入用户密码', trigger: 'blur' },
                        { pattern: /^[^\u4e00-\u9fa5]+$/, message: '不允许输入中文',trigger: 'blur'},
                        { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号',trigger: 'blur'},
                        { pattern: /[0-9a-zA-Z]{1,6}/, message: '只可以输入数字和字母',trigger: 'blur'},
                        { min: 6, max: 6, message: '长度为6 个字符', trigger: 'blur' }
                    ],
                    userQPwd: [
                        { required: true, message: '请输入确认密码', trigger: 'blur' },
                        { required: true, message: '请输入用户密码', trigger: 'blur' },
                        { pattern: /^[^\u4e00-\u9fa5]+$/, message: '不允许输入中文',trigger: 'blur'},
                        { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: '不允许输入空格等特殊符号',trigger: 'blur'},
                        { pattern: /[0-9a-zA-Z]{1,6}/, message: '只可以输入数字和字母',trigger: 'blur'},
                        { min: 6, max: 6, message: '长度为6 个字符', trigger: 'blur' }
                    ],
                    userNm: [
                        { required: true, message: '请输入用户姓名', trigger: 'blur' }
                    ],
                    roleIds: [
                        { required: true, message: '请选择角色', trigger: 'change' }
                    ],
                    organIds: [
                        { required: true, message: '请选择医院', trigger: 'change' }
                    ],
                },
                roles:[],
                organs:[],
                showViewer: false,
                srcList:[],
            };
        },
        created() {
            this.getData();
        },
        components:{
            ElImageViewer
        },
        methods: {
            // 获取后台数据
            getData() {
                userData(this.query).then(res => {
                    if (res.success == true){
                        this.tableData = res.data;
                        this.pageTotal = res.total;
                    } else {
                        this.$message.error("查询失败！");
                        this.tableData = [];
                        this.pageTotal = 0;
                    }
                });
            },
            // 触发搜索按钮
            handleSearch() {
                this.$set(this.query, 'pageIndex', 1);
                this.getData();
            },
            // 触发重置按钮
            handleReset() {
                this.query.userId = "";
                this.query.userAcct = "";
                this.getData();
            },
            // 删除操作
            handleDelete(index, row) {
                // 二次确认删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                        //后台进行删除操作
                            let condition={
                                userAcct:row.userAcct
                            };
                            doDelete(condition).then(res => {
                                if (res.data==1){
                                    this.$message.success('删除成功');
                                    this.getData();
                                }else {
                                    this.$message.error('删除失败');
                                    this.getData();
                                }
                        });
                    })
                    .catch(() => {
                        this.$message({
                            message:'已取消删除'
                        });
                    });
            },
            // 多选操作
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            // 新增操作
            handleAdd() {
                this.imgStr = require('../../../../assets/upload.png');
                this.addForm = {};
                getRoles().then(res =>{
                    this.roles = res.data;
                });
                getOrgans().then(res =>{
                    this.organs = res.data;
                });
                this.addVisible = true;
            },
            /*新增用户*/
            saveAdd(){
                this.$refs['addForm'].validate((valid) => {
                    if (valid) {
                         //判断输入的密码和确认密码是否一致
                        if(this.addForm.userPwd!=this.addForm.userQPwd){//不一致
                            this.$message.error("请确认两次输入的密码是否一致？");
                        }else {//一致
                            this.isExistQuery.userAcct = this.addForm.userAcct;
                            isNotExists(this.isExistQuery).then(isNotExistsres => {
                                if (isNotExistsres.data) {//用户不存在
                                    if (this.imgStr!="static/img/upload.466ec9ef.png"){
                                        // 给addForm中设置对应图片属性  imgTp,imgData，imgLen
                                        //截取字符串
                                        let imgTp=this.imgStr.substring(this.imgStr.indexOf("/")+1,this.imgStr.indexOf(";"));
                                        let imgData=this.imgStr.substring(this.imgStr.indexOf(",")+1);
                                        this.addForm.imgTp=imgTp;
                                        this.addForm.imgData=imgData;
                                        this.addForm.imgLen=this.imgLen;
                                    };
                                    //新增form表单提交到后台
                                    this.addForm.roleIds = this.addForm.roleIds.toString();
                                    this.addForm.organIds = this.addForm.organIds.toString();
                                    doAdd(this.addForm).then(res => {
                                        if (res.data==1){
                                            this.addVisible=false;
                                            this.addForm={};
                                            this.getData();
                                            this.$message.success('保存成功');
                                        }else{
                                            this.$message.error('保存失败');
                                        }
                                    });
                                }else{//用户已存在
                                    this.$message.error('该用户已存在');
                                }
                            });
                        }
                    }
                });
            },
            // 编辑操作
            handleEdit(index, row) {
                this.editForm = {};
                this.idx = index;
                this.editForm = row;
                this.editForm.userPwd="";
                if (row.imgTp !== null && row.imgData !== null){//有头像
                    this.imgStrEdit="data:image/"+ this.editForm.imgTp +";base64," + this.editForm.imgData;
                }
                getRoles().then(res =>{
                    this.roles = res.data;
                });
                getOrgans().then(res =>{
                    this.organs = res.data;
                });
                /*element这个下拉框是需要数组类型 */
                if (this.editForm.roleIds.toString() != null){
                    this.editForm.roleIds = this.editForm.roleIds.toString().split(",");
                }
                if (this.editForm.organIds.toString() != null){
                    this.editForm.organIds = this.editForm.organIds.toString().split(",");
                }
                this.editVisible = true;
            },
            closeEdit(){//关闭编辑弹出框
                this.editVisible=false;
                this.editForm={};
                this.getData();
            },
            // 保存编辑
            saveEdit() {
                let queryEdit={
                    userAcct:this.editForm.userAcct,
                    userPwd: this.editForm.userPwd
                };
                //判断img是否是初始化的
                if (this.isUpdateImg == true && this.imgStrEdit != "static/img/upload.466ec9ef.png"){
                    let imgTpEdit=this.imgStrEdit.substring(this.imgStrEdit.indexOf("/")+1,this.imgStrEdit.indexOf(";"));
                    let imgDataEdit=this.imgStrEdit.substring(this.imgStrEdit.indexOf(",")+1);
                    console.log(imgDataEdit);
                    this.editForm.imgTp=imgTpEdit;
                    this.editForm.imgData=imgDataEdit;
                    this.editForm.imgLen=this.imgLenEdit;
                }
                this.editForm.roleIds = this.editForm.roleIds.toString();
                this.editForm.organIds = this.editForm.organIds.toString();
                doUpdate(this.editForm).then(res => {
                    if (res.data == 1) {
                        this.editVisible = false;
                        this.editForm = {};
                        this.getData();
                        this.$message.success('编辑成功');
                    } else {
                        this.$message.error('编辑失败');
                    }
                });
                //
                // this.editVisible = false;
                // this.$message.success(`修改第 ${this.idx + 1} 行成功`);
                // this.$set(this.tableData, this.idx, this.form);
            },
            /*表单重置*/
            resetForm(refname){
                if (this.$refs[refname] !== undefined){
                    this.$refs[refname].resetFields();
                }
            },
            // 分页导航
            handlePageChange(val) {
                this.$set(this.query, 'pageIndex', val);
                this.getData();
            },
            /*头像上传 新增时*/
            onchangeImgFun (e) {
                let file = e.target.files[0];
                // 获取图片的大小，做大小限制有用
                let imgSize = file.size;
                let _this = this;// this指向问题，所以在外面先定义
                // 比如上传头像限制5M大小，这里获取的大小单位是b
                if (imgSize <= 5000 * 1024) {
                    // base64方法 2
                    let reader = new FileReader();
                    reader.readAsDataURL(file); // 读出 base64
                    reader.onloadend = function () {
                        // 图片的 base64 格式, 可以直接当成 img 的 src 属性值
                        let dataURL = reader.result;
                        _this.imgStr = dataURL;
                        _this.imgLen=imgSize;

                    }
                } else {
                    this.$message.error(`图片大小超出范围`);
                }
            },
            /*头像上传 编辑时 需修改*/
            onchangeImgFunEdit (e) {
                this.isUpdateImg = true;
                let file = e.target.files[0];
                // 获取图片的大小，做大小限制有用
                let imgSize = file.size;
                let _this = this;// this指向问题，所以在外面先定义
                // 比如上传头像限制5M大小，这里获取的大小单位是b
                if (imgSize <= 5000 * 1024) {
                    // base64方法 2
                    let reader = new FileReader();
                    reader.readAsDataURL(file); // 读出 base64
                    reader.onloadend = function () {
                        // 图片的 base64 格式, 可以直接当成 img 的 src 属性值
                        let dataURL = reader.result;
                        _this.imgStrEdit = dataURL;
                        _this.imgLenEdit=imgSize;
                    }
                } else {
                    this.$message.error(`图片大小超出范围`);
                }
            },
            onPreview(data) {
                this.showViewer = true;
                this.srcList[0]=data;
            },
            closeViewer() {
                this.showViewer = false
            },

        }
    };
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }
    .table {
        width: 100%;
        font-size: 14px;
    }
    .red {
        color: #ff0000;
    }
    .mr10 {
        margin-right: 10px;
    }
    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
        /*border-radius 属性允许您为元素添加圆角边框！*/
        border-radius:6px;
        background-clip:padding-box;
        border-top-left-radius: 6px;
        border-top-right-radius: 6px;
        border-bottom-right-radius: 6px;
        border-bottom-left-radius: 6px;
    }
    /*头像上传*/
    .user-header{
        position: relative;
        display: inline-block;
    }
    .user-header-com{
        width: 100px;
        height: 100px;
        border-radius: 50%;
        display: inline-block;
    }
    .header-upload-btn{
        position: absolute;
        left: 0;
        top: 0;
        opacity: 0;
        /* 通过定位把input放在img标签上面，通过不透明度隐藏 */
    }
</style>
